import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 登录页面组件配置到路由
  {
    path: '/login',
    name: 'login',
    // webpack提供 懒加载的方式引入组件,直接import没有懒加载效果
    component: () => import('../views/login/login.vue')
  },
  // layout首页组件配置到路由
  {
    path: '/',
    name: 'layout',
    component: () => import('@/views/layout/layout.vue'),
    // 二级路由
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('@/views/home/home.vue')
      },
      {
        path: 'articles',
        name: 'articles',
        component: () => import('@/views/articles/articles.vue')
      },
      {
        path: 'edit/:id',
        name: 'edit',
        component: () => import('@/views/articles/articleEdit.vue')
      },
      {
        path: 'articleAdd',
        name: 'articleAdd',
        component: () => import('@/views/articles/articleAdd.vue')
      },
      {
        path: 'images',
        name: 'images',
        component: () => import('@/views/images/images.vue')
      },
      {
        path: 'comment',
        name: 'comment',
        component: () => import('@/views/comment/comment.vue')
      },
      {
        path: 'fans',
        name: 'fans',
        component: () => import('@/views/fans/fans.vue')
      },
      {
        path: 'setting',
        name: 'setting',
        component: () => import('@/views/setting/setting.vue')
      }
    ]
  },
  {
    path: '*',
    name: 'page404',
    component: () => import('@/views/page404/page404.vue')
  }
]

const router = new VueRouter({
  routes
})

// 需要登录才能访问的页面
const authPageLsit = ['/', '/articles', '/image', '/addArticle', '/comment', '/fans', '/setting']
// 路由导航守卫
router.beforeEach((to, from, next) => {
  console.log('路由从' + from.path + '到' + to.path)
  // 判断地址是否是需要登录
  if (authPageLsit.includes(to.path)) {
    // 判断是否有token
    if (localStorage.getItem('tokenStr')) {
      // 需要登录 且有token - 放行
      next()
      // 没有token - 回到登陆页面
    } else {
      next('/login')
    }
    // 不需要登录 - 已经登录了就不能进入登录页面
  } else {
    // 去登陆页面,有token代表已经登录,留在主页页面
    if (to.path === '/login' && localStorage.getItem('tokenStr')) {
      next('/')
    } else {
      // 不是保存的需要登录的页面  - 放行 - 会走到404页面
      next()
    }
  }
})

export default router
